<script setup >
import { computed } from 'vue'
import router from '@/router'
import { useUserStore } from '@/stores'
import { clearToken } from '@/utils/auth'
import { showDialog, showSuccessToast } from 'vant'
import defaultAvatar from '@/assets/images/default-avatar.svg'

const userStore = useUserStore()
const userInfo = computed(() => userStore.userInfo)
const isLogin = computed(() => !!userInfo.value.uid)

function login() {
  if (isLogin.value)
    return

  router.push({ name: 'Login', query: { redirect: 'Profile' } })
}

// 退出登录
async function logout() {
  try {
    await showDialog({
      title: '确认退出',
      message: '确定要退出登录吗？',
      showCancelButton: true,
      confirmButtonText: '退出',
      cancelButtonText: '取消',
      confirmButtonColor: '#ee0a24'
    })
    
    // 清空用户store
    await userStore.logout()
    
    // 清空本地缓存
    clearToken()
    localStorage.removeItem('user_info')
    localStorage.removeItem('user_tokens')
    
    showSuccessToast('已退出登录')
    
    // 跳转到登录页
    router.push({ name: 'Login' })
    
  } catch (error) {
    // 用户取消退出
    console.log('用户取消退出')
  }
}
</script>

<template>
  <div>
    <VanCellGroup :inset="true">
      <van-cell center :is-link="!isLogin" @click="login">
        <template #title>
          <van-image :src="userInfo.avatar || defaultAvatar" round class="h-56 w-56" />
        </template>

        <template #value>
          <span v-if="isLogin">{{ userInfo.nickname }}</span>
          <span v-else>{{ $t('profile.login') }}</span>
        </template>
      </van-cell>
    </VanCellGroup>

    <VanCellGroup v-if="false" :inset="true" class="!mt-16">
      <van-cell :title="$t('profile.settings')" icon="setting-o" is-link to="/settings">
        <template #icon>
          <div class="i-carbon:settings text-gray-400 mr-5 self-center" />
        </template>
      </van-cell>
      <van-cell :title="$t('profile.docs')" is-link url="https://vue-zone.github.io/docs/vue3-vant-mobile/">
        <template #icon>
          <div class="i-carbon:doc text-gray-400 mr-5 self-center" />
        </template>
      </van-cell>
    </VanCellGroup>

    <!-- 退出登录按钮 -->
    <VanCellGroup :inset="true" class="!mt-16" v-if="isLogin">
      <van-cell 
        :title="$t('profile.logout') || '退出登录'" 
        icon="close" 
        @click="logout"
        class="logout-cell"
      >
        <template #icon>
          <div class="i-carbon:close text-red-400 mr-5 self-center" />
        </template>
      </van-cell>
    </VanCellGroup>
  </div>
</template>

<style scoped>
.logout-cell {
  color: #ee0a24;
}

.logout-cell :deep(.van-cell__title) {
  color: #ee0a24;
}
</style>

<route lang="json5">
{
  name: 'Profile'
}
</route>
